<template>
  <div class="cart-container">
    <el-card class="cart-header">
      <div class="header-content">
        <h2><el-icon><ShoppingCart /></el-icon> 我的购物车</h2>
        <el-button
          type="danger"
          :icon="Delete"
          :disabled="cartStore.cartItems.length === 0"
          @click="handleClearCart"
        >
          清空购物车
        </el-button>
      </div>
    </el-card>

    <el-card class="cart-content" v-loading="cartStore.loading">
      <el-empty v-if="cartStore.cartItems.length === 0" description="购物车是空的，快去选购吧~" />

      <transition-group name="cart-item" tag="div" class="cart-items">
        <div class="cart-item" v-for="item in cartStore.cartItems" :key="item.cartId">
          <div class="item-image">
            <img
              :src="getImageUrl(item.dish?.dishImage || '')"
              @error="handleImageError"
            />
          </div>
          <div class="item-info">
            <h3 class="item-name">{{ item.dish?.dishName }}</h3>
            <p class="item-type">{{ item.dish?.dishType }}</p>
          </div>
          <div class="item-price">
            <span class="price">¥{{ item.dish?.dishPrice }}</span>
          </div>
          <div class="item-quantity">
            <el-input-number
              v-model="item.quantity"
              :min="1"
              :max="99"
              @change="handleQuantityChange(item)"
            />
          </div>
          <div class="item-subtotal">
            <span class="subtotal">¥{{ ((item.dish?.dishPrice || 0) * item.quantity).toFixed(2) }}</span>
          </div>
          <div class="item-actions">
            <el-button
              type="danger"
              :icon="Delete"
              circle
              @click="handleRemoveItem(item)"
            />
          </div>
        </div>
      </transition-group>
    </el-card>

    <el-card class="cart-summary" v-if="cartStore.cartItems.length > 0">
      <div class="summary-content">
        <div class="summary-info">
          <div class="summary-item">
            <span>商品数量：</span>
            <span class="value">{{ cartStore.cartCount }} 件</span>
          </div>
          <div class="summary-item total">
            <span>总计：</span>
            <span class="total-price">¥{{ cartStore.totalAmount.toFixed(2) }}</span>
          </div>
        </div>
        <el-button
          type="primary"
          size="large"
          :icon="Checked"
          @click="showOrderDialog = true"
          class="checkout-btn"
        >
          去下单
        </el-button>
      </div>
    </el-card>

    <!-- 下单对话框 -->
    <el-dialog
      v-model="showOrderDialog"
      title="填写订单信息"
      width="500px"
      @close="resetOrderForm"
    >
      <el-form :model="orderForm" :rules="orderRules" ref="orderFormRef" label-width="100px">
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="orderForm.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="orderForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="配送地址" prop="deliveryAddress">
          <el-input
            v-model="orderForm.deliveryAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="orderForm.remark"
            type="textarea"
            :rows="2"
            placeholder="选填，如有特殊要求请备注"
          />
        </el-form-item>
        <el-form-item label="订单总额">
          <span class="order-total">¥{{ cartStore.totalAmount.toFixed(2) }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showOrderDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitOrder" :loading="submitting">提交订单</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ShoppingCart, Delete, Checked } from '@element-plus/icons-vue';
import { useCartStore } from '@/stores/cart';
import { useUserStore } from '@/stores/user';
import { createOrder, createOrderDetail, getOrdersByUserId } from '@/api/order';
import type { CartItem } from '@/types';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const cartStore = useCartStore();
const userStore = useUserStore();

const showOrderDialog = ref(false);
const submitting = ref(false);
const orderFormRef = ref<FormInstance>();

const orderForm = reactive({
  contactName: '',
  contactPhone: '',
  deliveryAddress: '',
  remark: ''
});

const orderRules: FormRules = {
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  deliveryAddress: [
    { required: true, message: '请输入配送地址', trigger: 'blur' }
  ]
};

// 数量变化处理
const handleQuantityChange = async (item: CartItem) => {
  if (!userStore.userId) return;
  await cartStore.updateQuantity(userStore.userId, item.cartId!, item.quantity);
};

// 删除商品
const handleRemoveItem = async (item: CartItem) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    if (!userStore.userId) return;
    await cartStore.removeItem(userStore.userId, item.cartId!);
  }).catch(() => {});
};

// 清空购物车
const handleClearCart = () => {
  ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    if (!userStore.userId) return;
    await cartStore.clearCart(userStore.userId);
  }).catch(() => {});
};

// 提交订单
const handleSubmitOrder = async () => {
  if (!orderFormRef.value) return;
  
  await orderFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    if (!userStore.userId) {
      ElMessage.warning('请先登录');
      return;
    }

    submitting.value = true;
    try {
      // 第一步：创建订单
      const orderResponse = await createOrder({
        userId: userStore.userId,
        contactName: orderForm.contactName,
        contactPhone: orderForm.contactPhone,
        deliveryAddress: orderForm.deliveryAddress,
        remark: orderForm.remark
      });

      if (orderResponse.operateResult === 'SUCC') {
        // 从响应中获取订单ID（需要从后端返回订单ID）
        // 由于当前后端只返回成功消息，我们需要通过其他方式获取订单ID
        // 这里我们先获取用户最新的订单ID
        const latestOrderResponse = await getOrdersByUserId(userStore.userId);
        if (latestOrderResponse.operateResult === 'SUCC' && latestOrderResponse.data && latestOrderResponse.data.length > 0) {
          const latestOrder = latestOrderResponse.data[0]; // 获取最新的订单
          const orderId = latestOrder.orderId;
          
          // 第二步：创建订单详情
          const detailResponse = await createOrderDetail(orderId);
          if (detailResponse.operateResult === 'SUCC') {
            // 第三步：清空购物车
            await cartStore.clearCart(userStore.userId);
            
            ElMessage.success('下单成功！请前往支付');
            showOrderDialog.value = false;
            // 跳转到待支付订单页面
            router.push('/user/pending-orders');
          } else {
            ElMessage.error('订单详情创建失败：' + (detailResponse.errorMsg || '未知错误'));
          }
        } else {
          ElMessage.error('无法获取订单信息');
        }
      } else {
        ElMessage.error(orderResponse.errorMsg || '下单失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '下单失败');
    } finally {
      submitting.value = false;
    }
  });
};

// 重置订单表单
const resetOrderForm = () => {
  orderFormRef.value?.resetFields();
  // 清除表单验证错误
  orderFormRef.value?.clearValidate();
};

// 获取图片URL
const getImageUrl = (imagePath: string) => {
  if (!imagePath || !imagePath.trim()) {
    return 'https://via.placeholder.com/100x100?text=No+Image';
  }
  if (imagePath.startsWith('http')) {
    return imagePath;
  }
  return `http://localhost:8060${imagePath}`;
};

// 图片加载错误处理
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  target.src = 'https://via.placeholder.com/100x100?text=No+Image';
};

onMounted(() => {
  if (userStore.userId) {
    cartStore.loadCart(userStore.userId);
  }
});
</script>

<style scoped>
.cart-container {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.cart-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #303133;
}

.cart-content {
  min-height: 400px;
  margin-bottom: 20px;
}

.cart-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.cart-item:hover {
  background-color: #e6e8eb;
  transform: translateX(5px);
}

.cart-item-enter-active,
.cart-item-leave-active {
  transition: all 0.3s ease;
}

.cart-item-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.cart-item-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

.item-image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 20px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
  margin-right: 20px;
}

.item-name {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #303133;
}

.item-type {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.item-price {
  min-width: 100px;
  text-align: center;
}

.price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.item-quantity {
  min-width: 150px;
  text-align: center;
}

.item-subtotal {
  min-width: 120px;
  text-align: center;
}

.subtotal {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
}

.item-actions {
  min-width: 60px;
  text-align: center;
}

.cart-summary {
  position: sticky;
  bottom: 20px;
  animation: slideUp 0.5s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.summary-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-info {
  display: flex;
  gap: 40px;
  align-items: center;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  color: #606266;
}

.summary-item .value {
  font-weight: bold;
  color: #303133;
}

.summary-item.total {
  font-size: 18px;
}

.total-price {
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
}

.checkout-btn {
  min-width: 150px;
  height: 50px;
  font-size: 16px;
}

.order-total {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
}
</style>
